package org.wms.minbearwcs.serivce.mission.processor.inbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import org.wms.minbearwcs.dao.inbound.inf.InboundOrderDetailDao;
import org.wms.minbearwcs.dao.mission.inf.WcsMissionDao;
import org.wms.minbearwcs.entity.DTO.agv.task.AgvActionSource;
import org.wms.minbearwcs.entity.DTO.agv.task.AgvTaskSource;
import org.wms.minbearwcs.entity.DTO.agv.task.actionEnum.AgvAction;
import org.wms.minbearwcs.entity.DTO.transfer.Tuple;
import org.wms.minbearwcs.entity.PO.agv.missionEnum.AgvMissionType;
import org.wms.minbearwcs.entity.PO.wcs.inbound.InboundOrderDetail;
import org.wms.minbearwcs.entity.PO.wcs.mission.WcsMission;
import org.wms.minbearwcs.entity.PO.wcs.mission.status.InboundMissionFor3Or4FloorStatus;
import org.wms.minbearwcs.entity.PO.wcs.mission.type.MissionType;
import org.wms.minbearwcs.resource.WcsResource;
import org.wms.minbearwcs.serivce.agv.task.agvTask.AgvTaskDispatcher;
import org.wms.minbearwcs.serivce.mission.processor.MissionProcessor;
import org.wms.minbearwcs.serivce.mission.processor.MissionProcessorCommonUtil;
import org.wms.minbearwcs.serivce.mission.storageProcessor.locker.Floor3Or4.Storage3Or4FloorLocker;
import org.wms.minbearwcs.utils.IdWorker;

import java.time.LocalDateTime;

@Slf4j
@Component
@RequiredArgsConstructor
public class Inbound3Or4FloorMissionProcessor implements MissionProcessor {

    private final InboundOrderDetailDao inboundOrderDetailDao;
    private final AgvTaskDispatcher getPutTaskDispatcher;
    private final TransactionTemplate transactionTemplate;
    private final WcsMissionDao wcsMissionDao;
    private final WcsResource wcsResource;
    private final IdWorker idWorker;
    private final Storage3Or4FloorLocker storage3Or4FloorLocker;
    private final MissionProcessorCommonUtil commonUtil;


    private final Object lock = new Object();


    @Override
    public MissionType getMissionType() {
        return MissionType.INBOUND_3_OR_4_FLOOR;
    }

    @Override
    public void process(WcsMission missionInfo) {
        InboundMissionFor3Or4FloorStatus missionStatus = (InboundMissionFor3Or4FloorStatus) missionInfo.getEnumMissionStatus();

        switch (missionStatus) {
            case WAIT_FOR_DISPATCH:
                dispatchAgvTask(missionInfo);
                break;
            case DISPATCHING:
                break;
            case PROCESSING:
                monitorMission(missionInfo);
                break;
            case FINISH:
                finishWcsMission(missionInfo);
                break;
            case CANCEL:
                break;
        }
    }


    public InboundOrderDetail getOrderDetail(Integer detailId) {
        return inboundOrderDetailDao.selectById(detailId);
    }

    public boolean statusChange(Integer missionId, InboundMissionFor3Or4FloorStatus oldStatus, InboundMissionFor3Or4FloorStatus newStatus) {
        return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
            try {
                if (oldStatus == wcsMissionDao.selectMissionStatusById(missionId)) {
                    synchronized (lock) {
                        if (oldStatus == wcsMissionDao.selectMissionStatusById(missionId)) {
                            wcsMissionDao.updateMissionStatusById(missionId, newStatus.name());
                            wcsMissionDao.updateStartTime(missionId, LocalDateTime.now());
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("wcs任务状态转换出错", e);
                status.setRollbackOnly();
            }
            return false;
        }));
    }


    public void dispatchAgvTask(WcsMission missionInfo) {
        if (!statusChange(missionInfo.getId(),
                InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH,
                InboundMissionFor3Or4FloorStatus.DISPATCHING
        )) return;

        InboundOrderDetail orderDetail = getOrderDetail(missionInfo.getAssociatedDetailId());


        wcsResource.getExecutor().execute(() -> {
            Tuple<String> lockTuple = transactionTemplate.execute(status -> {
                try {
                    Tuple<String> temp = storage3Or4FloorLocker.lockStorage(orderDetail.getStoragePoint(), orderDetail.getPalletCode());
                    if (!temp.success) {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name());
                        return Tuple.tuple(null, false);
                    }
                    return temp;
                } catch (Exception e) {
                    log.error("3F/4F储位 {} 锁定失败", orderDetail.getStoragePoint(), e);
                    status.setRollbackOnly();
                    return Tuple.tuple(null, false);
                }
            });

            Boolean executeRes = transactionTemplate.execute(status -> {
                try {
                    String agvTaskId = "Task_Agv_" + idWorker.nextId();
                    AgvTaskSource agvTaskSource = new AgvTaskSource(agvTaskId, AgvMissionType.GET_REQLIFT_PASS_PUT, 1, missionInfo.getMissionId(), missionInfo.getMissionType(),
                            InboundMissionFor3Or4FloorStatus.PROCESSING.name());
                    agvTaskSource.addAction(new AgvActionSource(orderDetail.getStartPoint(), AgvAction.GET))
                            .addAction(new AgvActionSource(orderDetail.getLiftRequestPoint(), AgvAction.LIFT_REQUEST))
                            .addAction(new AgvActionSource(lockTuple.value, AgvAction.PASS))
                            .addAction(new AgvActionSource(orderDetail.getStoragePoint(), AgvAction.PUT));


                    if (getPutTaskDispatcher.dispatch(agvTaskSource)) {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.PROCESSING.name());
                    } else {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name());
                    }
                    return true;
                } catch (Exception e) {
                    log.error("wcs任务：{}，生成agv任务失败", missionInfo.getMissionId(),e);
                    status.setRollbackOnly();
                    return false;
                }
            });

            if (Boolean.FALSE.equals(executeRes)) {
                transactionTemplate.executeWithoutResult(status->{
                    storage3Or4FloorLocker.unLockStorage(orderDetail.getPalletCode());
                    wcsMissionDao.updateMissionStatusById(missionInfo.getId(), InboundMissionFor3Or4FloorStatus.WAIT_FOR_DISPATCH.name());
                });
            }

        });
    }


    public void monitorMission(WcsMission missionInfo) {

    }

    public void finishWcsMission(WcsMission missionInfo) {
        transactionTemplate.executeWithoutResult(status -> {
            try {
                missionInfo.setFinishTime(LocalDateTime.now());
                commonUtil.transformMissionHistory(missionInfo);
            } catch (Exception e) {
                log.error("任务结束错误", e);
                status.setRollbackOnly();
            }
        });

    }

}
